package com.sun.mvc.controller;

import com.sun.mvc.bean.Employee;
import com.sun.mvc.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    // 查询所有员工列表
    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getEmployeeList(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList", employeeList);
        return "employee_list";
    }

    // 根据id删除员工信息
    @RequestMapping(value = "/employee/{id}")
    public String deleteEmployeeById(@PathVariable(value = "id") Integer id){
        employeeDao.delete(id);
        return "redirect:/employee";
    }

    // 添加员工
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    // 根据Id修改员工信息
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String updateEmployeeById(@PathVariable(value = "id")Integer id, Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee", employee);
        return "employee_update";
    }

    @RequestMapping(value = "/employee", method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

}
